package com.findfuture.demo.controller;

import com.findfuture.common.util.FileUploadUtils;
import com.findfuture.common.util.StringUtil;
import com.findfuture.demo.model.Albums;
import com.findfuture.demo.model.Images;
import com.findfuture.demo.service.IAlbumService;
import com.findfuture.demo.service.ICatalogService;
import com.findfuture.demo.service.IImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Alex
 * Date: 11-12-19
 * Time: 下午8:54
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/image")
@SessionAttributes("token")
public class ImageController {

    @Autowired
    private IImageService imageService;

    @Autowired
    private IAlbumService albumService;

    @Autowired
    private ICatalogService catalogService;

    @RequestMapping("/{id}")
    public String list(ModelMap modelMap, @PathVariable int id) throws Exception {

        modelMap.addAttribute("token", StringUtil.uuid());
        modelMap.addAttribute("album", albumService.getAlbumsById(id));
        return "/image/images";
    }

    @RequestMapping("/deleteImage/{imageId}/{albumId}/{token}")
    public String deleteImage(ModelMap modelMap, @PathVariable int imageId, @PathVariable int albumId,
                              @PathVariable String token, @ModelAttribute("token") String sessionToken) {
        if (token.equals(sessionToken)) {
            try {
                imageService.deleteImage(imageId);
                modelMap.addAttribute("success", "操作成功！");
            } catch (Exception e) {
                e.printStackTrace();
                modelMap.addAttribute("error", "操作失败！");
            }
        }
        return "forward:/image/" + albumId;
    }

    @RequestMapping("/upload/{albumId}")
    public String upload(@PathVariable int albumId, ModelMap modelMap) {
        modelMap.put("albumId", albumId);
        return "image/upload";
    }

    @RequestMapping("/batchUpload/{albumId}")
    public String batchUpload(@PathVariable int albumId, ModelMap modelMap) {
        modelMap.put("albumId", albumId);
        return "image/batchUpload";
    }

    @RequestMapping("/update/{imageId}")
    public String update(@PathVariable int imageId, ModelMap modelMap) {
        modelMap.put("image", imageService.getImageById(imageId));
        return "/image/upload";
    }

    @RequestMapping("/updateAction")
    public String updateAction(MultipartHttpServletRequest request, int albumId, int imageId, String desc, float price, String name, String token, @ModelAttribute("token") String sessionToken, ModelMap modelMap) {
        if (token.equals(sessionToken)) {
            Images images = imageService.getImageById(imageId);
            try {
//            DiskFileItemFactory factory = new DiskFileItemFactory();
//            // 设置内存缓冲区，超过后写入临时文件
//            factory.setSizeThreshold(10240000);
                String uploadpath = request.getSession().getServletContext()
                        .getRealPath("uploadfile");
                System.out.println("uploadpath :" + uploadpath);
                CommonsMultipartFile file = (CommonsMultipartFile) request.getFile("file");
                String fileName = file.getOriginalFilename();
                if (!file.isEmpty()) {
                    InputStream stream = file.getInputStream();
                    if (desc == null || desc.equals("")) {
                        desc = fileName.split("\\.")[0];
                    }
                    String type = FileUploadUtils.getPostfix(fileName);
                    //防止中文乱码重新进行命名
                    fileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    //图片保存到文件夹操作

                    String path = uploadpath + "/" + "images" + "/" + albumId;
                    String thumb = uploadpath + "/" + "thumb/" + albumId;
                    //检查文件夹是否存在
                    FileUploadUtils.createDir(path);
                    FileUploadUtils.createDir(thumb);
                    String fileNameFull = path + File.separator + fileName;
                    System.out.println(fileNameFull);
                    OutputStream bos = new FileOutputStream(fileNameFull);
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                    }
                    bos.close();
                    // 关闭流
                    stream.close();
                    FileUploadUtils.Thumbnail(fileNameFull, thumb + File.separator + fileName, 200, 180, 100);
                }

                images.setDescript(desc);
                images.setName(name);
                images.setPrice(price);
                if (!file.isEmpty()) {
                    FileUploadUtils.deleteWebAppFile(images.getUrl());
                    FileUploadUtils.deleteWebAppFile(images.getThumb());
                    images.setUrl("uploadfile/images/" + albumId + "/" + fileName);
                    images.setThumb("uploadfile/thumb/" + albumId + "/" + fileName);
                }
                imageService.updateImage(images);
                modelMap.addAttribute("success", "产品修改成功！");
            } catch (Exception e) {
                e.printStackTrace();
                modelMap.addAttribute("error", "产品修改失败！");
            }
        }
        return "forward:/image/" + albumId;
    }

    @RequestMapping("/uploadImage")
    public String uploadImage(MultipartHttpServletRequest request, int albumId, String desc, float price, String name, String token, @ModelAttribute("token") String sessionToken, ModelMap modelMap) {
        if (token.equals(sessionToken)) {
            try {
//            DiskFileItemFactory factory = new DiskFileItemFactory();
//            // 设置内存缓冲区，超过后写入临时文件
//            factory.setSizeThreshold(10240000);
                String uploadpath = request.getSession().getServletContext()
                        .getRealPath("uploadfile");
                System.out.println("uploadpath :" + uploadpath);
                CommonsMultipartFile file = (CommonsMultipartFile) request.getFile("file");
                String fileName = file.getOriginalFilename();
                if (!file.isEmpty()) {
                    InputStream stream = file.getInputStream();
                    if (desc == null || desc.equals("")) {
                        desc = fileName.split("\\.")[0];
                    }
                    String type = FileUploadUtils.getPostfix(fileName);
                    //防止中文乱码重新进行命名
                    fileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    //图片保存到文件夹操作

                    String path = uploadpath + "/" + "images" + "/" + albumId;
                    String thumb = uploadpath + "/" + "thumb/" + albumId;
                    //检查文件夹是否存在
                    FileUploadUtils.createDir(path);
                    FileUploadUtils.createDir(thumb);
                    String fileNameFull = path + File.separator + fileName;
                    System.out.println(fileNameFull);
                    OutputStream bos = new FileOutputStream(fileNameFull);
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                    }
                    bos.close();
                    // 关闭流
                    stream.close();
                    FileUploadUtils.Thumbnail(fileNameFull, thumb + File.separator + fileName, 200, 180, 100);
                }

                Images images = new Images();
                Albums albums = albumService.getAlbumsById(albumId);
                images.setImageAlbum(albums);
                images.setDescript(desc);
                images.setName(name);
                images.setPrice(price);
                if (file.isEmpty()) {
                    images.setUrl("assets/no_photo.png");
                    images.setThumb("assets/no_photo_s.png");
                } else {
                    images.setUrl("uploadfile/images/" + albumId + "/" + fileName);
                    images.setThumb("uploadfile/thumb/" + albumId + "/" + fileName);
                }
                imageService.addImage(images);
                modelMap.addAttribute("success", "产品添加成功！");
            } catch (Exception e) {
                modelMap.addAttribute("error", "产品添加失败！");
                e.printStackTrace();
            }
        }
        return "forward:/image/" + albumId;
    }

    @RequestMapping("/batchUploadImage")
    public String batchUploadImage(MultipartHttpServletRequest request, int albumId, ModelMap modelMap) {
        try {
            String desc = "";
//            DiskFileItemFactory factory = new DiskFileItemFactory();
//            // 设置内存缓冲区，超过后写入临时文件
//            factory.setSizeThreshold(10240000);
            String uploadpath = request.getSession().getServletContext()
                    .getRealPath("uploadfile");
            System.out.println("uploadpath :" + uploadpath);
            CommonsMultipartFile file = (CommonsMultipartFile) request.getFile("file");
            String fileName = file.getOriginalFilename();
            if (!file.isEmpty()) {
                InputStream stream = file.getInputStream();
                desc = fileName.split("\\.")[0];

                String type = FileUploadUtils.getPostfix(fileName);
                //防止中文乱码重新进行命名
                fileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                //图片保存到文件夹操作

                String path = uploadpath + "/" + "images" + "/" + albumId;
                String thumb = uploadpath + "/" + "thumb/" + albumId;
                //检查文件夹是否存在
                FileUploadUtils.createDir(path);
                FileUploadUtils.createDir(thumb);
                String fileNameFull = path + File.separator + fileName;
                System.out.println(fileNameFull);
                OutputStream bos = new FileOutputStream(fileNameFull);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.close();
                // 关闭流
                stream.close();
                FileUploadUtils.Thumbnail(fileNameFull, thumb + File.separator + fileName, 200, 180, 100);
            }

            Images images = new Images();
            Albums albums = albumService.getAlbumsById(albumId);
            images.setImageAlbum(albums);
            images.setDescript(desc);
            images.setName(desc);
            images.setPrice(0);
            if (file.isEmpty()) {
                images.setUrl("assets/no_photo.png");
                images.setThumb("assets/no_photo_s.png");
            } else {
                images.setUrl("uploadfile/images/" + albumId + "/" + fileName);
                images.setThumb("uploadfile/thumb/" + albumId + "/" + fileName);
            }
            imageService.addImage(images);
            modelMap.addAttribute("success", "产品添加成功！");
        } catch (Exception e) {
            modelMap.addAttribute("error", "产品添加失败！");
            e.printStackTrace();
        }

        return "forward:/image/" + albumId;
    }

    @RequestMapping("/updateTop/{imageId}/{albumId}/{token}")
    public String updateTop(ModelMap modelMap, @PathVariable int imageId, @PathVariable int albumId, @PathVariable String token, @ModelAttribute("token") String sessionToken) {
        if (token.equals(sessionToken))
            try {
                Images images = imageService.getImageById(imageId);
                int top = images.getTop();
                if (top == 1) {
                    images.setTop(0);
                } else {
                    images.setTop(1);
                }
                imageService.updateImage(images);
                modelMap.addAttribute("success", "修改轮循成功！");
            } catch (Exception e) {
                modelMap.addAttribute("error", "修改轮循失败！");
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        return "forward:/image/" + albumId;
    }
}
